#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <iostream>
#include <thread>
#include <vector>
#include "TaskQueue.h"

using std::vector;
using std::thread;

class ThreadPool {
private:
    using Task = function<void()>;

    size_t _threadNum;      /*子线程数目*/
    vector<thread> _threads;/*存放线程的数据结构*/
    size_t _queueSize;      /*任务队列大小*/
    TaskQueue _taskQueue;   /*任务队列*/
    bool _isExit;           /*是否退出*/
public:
    ThreadPool(size_t threadNum, size_t queueSize) :
            _threadNum(threadNum), _queueSize(queueSize),
            _taskQueue(queueSize), _isExit(false) {

    }

    ~ThreadPool() {}

    void start() {
        for (size_t i = 0; i != _threadNum; ++i) {
            _threads.push_back(thread(&ThreadPool::doTask, this));
        }
    }

    void stop() {

        /* 任务队列不空则不能向下执行 */
        while(!_taskQueue.empty()){
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }

        _isExit = true;

        _taskQueue.wakeup();
        for (auto &elem: _threads) {
            elem.join();
        }
    }

    void addTask(Task&& taskcb) {
        if (taskcb) {
            _taskQueue.push(std::move(taskcb));
        }
    }

private:
    Task getTask() {
        return _taskQueue.pop();
    }

    void doTask() {
        while (!_isExit) {
            Task taskcb = getTask();
            if (taskcb) {
                taskcb();    /* 回调 */
            }
        }
    }
};


#endif //THREADPOOL_H
